#include "task_parser.h"
#include <iostream>
#include <sstream>

bool TaskParser::ParseTask(const std::string& json, nanok::Task& task) {
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::istringstream iss(json);
    std::string errs;
    if (!Json::parseFromStream(builder, iss, &root, &errs)) {
        std::cerr << "Failed to parse JSON: " << errs << std::endl;
        return false;
    }
    try {
        // 解析 metadata
        if (root.isMember("metadata")) {
            Json::Value metadata = root["metadata"];
            task.metadata.name = metadata["name"].asString();
            task.metadata.namespace_ = metadata["namespace"].asString();
            task.metadata.resourceVersion = metadata["resourceVersion"].asInt64();
        }
        // 解析 spec
        if (root.isMember("spec")) {
            Json::Value spec = root["spec"];
            task.spec.podName = spec["podName"].asString();
            task.spec.assignedNode = spec["assignedNode"].asString();
        }        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Error parsing Pod: " << e.what() << std::endl;
        return false;
    }
}

bool TaskParser::ParseTaskList(const std::string& json, std::vector<nanok::Task>& tasks) {
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::istringstream iss(json);
    std::string errs;
    if (!Json::parseFromStream(builder, iss, &root, &errs)) {
        std::cerr << "Failed to parse JSON: " << errs << std::endl;
        return false;
    }
    try {
        // 检查是否是数组
        if (root.isArray()) {
            for (const auto& item : root) {
                nanok::Task task;
                // 将每个数组元素转换为字符串并解析为 Pod
                Json::StreamWriterBuilder writer;
                std::string taskJson = Json::writeString(writer, item);
                if (ParseTask(taskJson, task)) {
                    tasks.push_back(task);
                }
            }
            return true;
        }
        // 如果不是数组，尝试解析为单个 Pod
        nanok::Task task;
        if (ParseTask(json, task)) {
            tasks.push_back(task);
            return true;
        }
        return false;
    } catch (const std::exception& e) {
        std::cerr << "Error parsing Pod list: " << e.what() << std::endl;
        return false;
    }
}

std::string TaskParser::ToJson(const nanok::Task& task) {
    Json::Value root;
    // 构建 metadata
    Json::Value metadata;
    metadata["name"] = task.metadata.name;
    metadata["namespace"] = task.metadata.namespace_;
    metadata["resourceVersion"] = task.metadata.resourceVersion;
    root["metadata"] = metadata;
    // 构建 spec
    Json::Value spec;
    spec["podName"] = task.spec.podName;
    spec["assignedNode"] = task.spec.assignedNode;
    root["spec"] = spec;
    Json::StreamWriterBuilder builder;
    return Json::writeString(builder, root);
}